package com.coolcode.advice;

import com.coolcode.common.ExceptionLogger;
import com.coolcode.enums.ExceptionErrorCode;
import com.coolcode.exception.ApiError;
import com.coolcode.exception.CriticalException;
import com.coolcode.exception.ValidationException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestControllerAdvice(basePackages = "com.coolcode.controller")
@Component
@Slf4j
public class GlobalExceptionHandler {

    @ResponseStatus(HttpStatus.FORBIDDEN)
    @ExceptionHandler(BindException.class)
    public ResponseEntity<Object> handleException(final BindException e) {

        ArrayList<String> messages = new ArrayList<>();
        for (ObjectError objectError : e.getAllErrors()) {
            if (objectError instanceof FieldError) {
                FieldError fieldError = (FieldError) objectError;
                messages.add(fieldError.getField() + " " + fieldError.getDefaultMessage());
            } else {
                messages.add(objectError.getDefaultMessage());
            }
        }

        ValidationException validationException = new ValidationException(ExceptionErrorCode.INVALID_INPUT.getCode(),
                String.format(ExceptionErrorCode.INVALID_INPUT.getDesc(), StringUtils.join(messages, "|")));
        ApiError apiError = buildApiError(validationException);
        return new ResponseEntity<>(apiError, HttpStatus.FORBIDDEN);
    }


    @ResponseStatus(HttpStatus.FORBIDDEN)
    @ExceptionHandler(ValidationException.class)
    public ResponseEntity<Object> handleException(final ValidationException e) {
        ApiError apiError = buildApiError(e);
        return new ResponseEntity<>(apiError, HttpStatus.FORBIDDEN);
    }

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(CriticalException.class)
    public ResponseEntity<Object> handleException(final CriticalException e) {
        ExceptionLogger.log(e);
        ApiError apiError = buildApiError(e);
        return new ResponseEntity<>(apiError, HttpStatus.INTERNAL_SERVER_ERROR);
    }


    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public ResponseEntity<Object> handleException(final Exception e) {
        ExceptionLogger.log(e);
        ApiError apiError = buildApiError(e);
        return new ResponseEntity<>(apiError, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    private ApiError buildApiError(Exception e) {
        String errorCode = ExceptionErrorCode.SYSTEM_ERROR.getCode();
        String errorMessage = ExceptionErrorCode.SYSTEM_ERROR.getDesc();

        if (e instanceof ValidationException) {
            ValidationException ex = (ValidationException) e;
            errorCode = ex.getErrorCode();
            errorMessage = ex.getMessage();
        } else if (e instanceof CriticalException) {
            CriticalException ex = (CriticalException) e;
            errorCode = ex.getErrorCode();
            errorMessage = ex.getMessage();
        }
        return new ApiError(errorCode, errorMessage);
    }

}
